package com.edu.study.base.stuQuestionLibrary.controller;

import cn.hutool.core.date.DateUtil;
import com.edu.base.common.utils.VideoUtil;
import com.edu.study.base.needfieldMetadata.domain.TbNeedfieldMetadataRy;
import com.edu.study.base.needfieldMetadata.service.ITbNeedfieldMetadataRyService;
import com.edu.study.base.questionKind.domain.StuQuestionKind;
import com.edu.study.base.questionKind.service.IStuQuestionKindService;
import com.edu.study.base.stuProductCatalog.domain.StuProductCatalog;
import com.edu.study.base.stuProductCatalog.service.IStuProductCatalogService;
import com.edu.study.base.stuQuestionLibrary.domain.StuQuestionLibraryRy;
import com.edu.study.base.stuQuestionLibrary.service.IStuQuestionLibraryRyService;
import com.edu.study.base.stuQuestionPaperRelation.service.IStuQuestionPaperRelationService;
import com.edu.study.base.stuQuestionRelation.domain.StuQuestionRelationRy;
import com.edu.study.base.stuQuestionRelation.service.IStuQuestionRelationRyService;
import com.edu.study.base.wordLibrary.domain.wordLibrary;
import com.edu.study.base.wordLibrary.service.IwordLibraryService;
import com.edu.study.base.wordLibrary.service.impl.wordLibraryServiceImpl;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.ffmpegUtils;
import com.ruoyi.common.utils.pdf.PdfUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * stuQuestionLibraryController
 *
 * @author jjt
 * @date 2021-02-27
 */
@RestController
@RequestMapping("/stu/questionLibrary")
public class StuQuestionLibraryRyController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(wordLibraryServiceImpl.class);
    @Autowired
    private IStuQuestionLibraryRyService stuQuestionLibraryRyService;

    @Autowired
    private ITbNeedfieldMetadataRyService needfieldMetadataRyService;

    @Autowired
    private IStuQuestionRelationRyService stuQuestionRelationRyService;
    @Autowired
    private IStuQuestionPaperRelationService stuQuestionPaperRelationService;
    @Autowired
    private IStuQuestionKindService stuQuestionKindService;

    @Autowired
    private IwordLibraryService wordLibraryService;
    @Autowired
    private IStuProductCatalogService productCatalogService;

    /**
     * 查询stuQuestionLibrary列表
     */
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:list')")
    @GetMapping("/list")
    public TableDataInfo list(StuQuestionLibraryRy stuQuestionLibraryRy) {
        startPage();
        List<StuQuestionLibraryRy> list = stuQuestionLibraryRyService.selectStuQuestionLibraryRyList(stuQuestionLibraryRy);
        return getDataTable(list);
    }

    @Log(title = "查询课文资源", businessType = BusinessType.OTHER)
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:list')")
    @GetMapping("/getStuCourseTextList")
    public TableDataInfo getStuCourseTextList(StuQuestionLibraryRy stuQuestionLibraryRy) {
        startPage();
        List<StuQuestionLibraryRy> list = stuQuestionLibraryRyService.selectStuCourseTextList(stuQuestionLibraryRy);
        return getDataTable(list);
    }

    @Log(title = "查询课程下的资源内容", businessType = BusinessType.OTHER)
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:list')")
    @GetMapping("/getStuCourseContentList")
    public TableDataInfo getStuCourseContentList(StuQuestionLibraryRy stuQuestionLibraryRy) {
        startPage();
        List<StuQuestionLibraryRy> list = stuQuestionLibraryRyService.selectStuCourseContentList(stuQuestionLibraryRy);
        TbNeedfieldMetadataRy tbNeedfieldMetadataRy = new TbNeedfieldMetadataRy();
        tbNeedfieldMetadataRy.setBussNo(stuQuestionLibraryRy.getBussNo());
        tbNeedfieldMetadataRy.setTableName(stuQuestionLibraryRy.getBussTableName());
        List<TbNeedfieldMetadataRy> metadataList = needfieldMetadataRyService.selectTbNeedfieldMetadataRyList(tbNeedfieldMetadataRy);
        StuQuestionKind stuQuestionKind = stuQuestionKindService.selectStuQuestionKindById(Long.parseLong(stuQuestionLibraryRy.getBussNo()));
        Map<String, Object> map = new HashMap<>();
        map.put("metadata", metadataList);//显示字段
        map.put("parseRule", stuQuestionKind);//题型解析规则
        return getDataTable(list, map);
    }


    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:list')")
    @GetMapping("/getPicturebookPageList")
    public TableDataInfo getPicturebookPageList(StuQuestionLibraryRy stuQuestionLibraryRy) {
        startPage();
        List<StuQuestionLibraryRy> list = stuQuestionLibraryRyService.getPicturebookPageList(stuQuestionLibraryRy);
        return getDataTable(list);
    }

    @GetMapping("/getTreeDetailInfoList")
    public Map getTreeDetailInfoList(StuQuestionLibraryRy stuQuestionLibraryRy) {
        Map resultMap = new HashMap();
        startPage();
        List<StuQuestionLibraryRy> list = stuQuestionLibraryRyService.getTreeDetailInfoList(stuQuestionLibraryRy);
        TableDataInfo data = getDataTable(list);
        //获取需要展示的字段
        TbNeedfieldMetadataRy tbNeedfieldMetadataRy = new TbNeedfieldMetadataRy();
        tbNeedfieldMetadataRy.setTableName("stu_question_library");
        tbNeedfieldMetadataRy.setBussNo(stuQuestionLibraryRy.getQuestionTypeId() + "");
        List<TbNeedfieldMetadataRy> metadataList = needfieldMetadataRyService.selectTbNeedfieldMetadataRyList(tbNeedfieldMetadataRy);

        StuQuestionKind stuQuestionKind = stuQuestionKindService.selectStuQuestionKindById(stuQuestionLibraryRy.getQuestionTypeId());
//        StuQuestionContentParseRule stuQuestionContentParseRule = new StuQuestionContentParseRule();
//        stuQuestionContentParseRule.setQuestionKindId(stuQuestionKindRyList.get(0).getId());
//        List<StuQuestionContentParseRule> ruleList = stuQuestionContentParseRuleService.selectStuQuestionContentParseRuleList(stuQuestionContentParseRule);
//        StuQuestionContentParseRule parseRule = null;
//        if(ruleList != null && ruleList.size() > 0){
//            parseRule = ruleList.get(0);
//        }
        resultMap.put("data", data);
        resultMap.put("metadataList", metadataList);
        resultMap.put("stuQuestionKind", stuQuestionKind);
//        if(stuQuestionKindRyList != null && stuQuestionKindRyList.size() > 0){
//            resultMap.put("stuQuestionKind",stuQuestionKindRyList.get(0));
//        }else{
//            resultMap.put("stuQuestionKind",null);
//        }
//        resultMap.put("parseRule",parseRule);
        return resultMap;
    }


    /**
     * 导出stuQuestionLibrary列表
     */
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:export')")
    @Log(title = "stuQuestionLibrary", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(StuQuestionLibraryRy stuQuestionLibraryRy) {
        List<StuQuestionLibraryRy> list = stuQuestionLibraryRyService.selectStuQuestionLibraryRyList(stuQuestionLibraryRy);
        ExcelUtil<StuQuestionLibraryRy> util = new ExcelUtil<StuQuestionLibraryRy>(StuQuestionLibraryRy.class);
        return util.exportExcel(list, "questionLibrary");
    }

    /**
     * 获取stuQuestionLibrary详细信息
     */
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(stuQuestionLibraryRyService.selectStuQuestionLibraryRyById(id));
    }

    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:query')")
    @GetMapping(value = "getById/{id}")
    public AjaxResult getById(@PathVariable("id") Long id) {
        return AjaxResult.success(stuQuestionLibraryRyService.selectStuQuestionLibraryRyInfoById(id));
    }

    //@Transactional(transactionManager = "slaveTransactionManager")
    @Transactional
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:add')")
    @Log(title = "添加课程相关资源", businessType = BusinessType.INSERT)
    @PostMapping("/addQuestionLibraryForCourse")
    public AjaxResult addQuestionLibraryForCourse(@RequestBody StuQuestionLibraryRy stuQuestionLibraryRy) throws Exception {

        stuQuestionLibraryRy = setProps(stuQuestionLibraryRy);

        return toAjax(AddStuQuestionLibrary(stuQuestionLibraryRy));
    }

    /**
     * 获取视频时长，添加字幕，提取视频中音频
     *
     * @param stuQuestionLibraryRy
     * @return
     */
    private StuQuestionLibraryRy setProps(StuQuestionLibraryRy stuQuestionLibraryRy) {
        String VideoUrl = stuQuestionLibraryRy.getQuestionVideoUrl();
        String videoSubtitleUrl = stuQuestionLibraryRy.getVideoSubtitleUrl();

        if (StringUtils.isNotEmpty(VideoUrl)) {
            try {
                Map map = VideoUtil.getVideoDetail(VideoUrl);
                //获取视频时长
                Double videoTime = Double.parseDouble(map.get("duration").toString());
                stuQuestionLibraryRy.setVideoTimeLength(videoTime);
                //提取视频中的音频
                String audioPath = ffmpegUtils.getAudioFromVideo(VideoUrl, "mp3");
                if (StringUtils.isNotEmpty(audioPath)) {
                    stuQuestionLibraryRy.setVideoBgm(audioPath);
                }
                //视频添加字幕
                if (StringUtils.isNotEmpty(videoSubtitleUrl)) {
                    String videoPath = RuoYiConfig.getProfile() + VideoUrl.substring(VideoUrl.indexOf("/upload"));
                    String subtitleFilePath = RuoYiConfig.getProfile() + videoSubtitleUrl.substring(videoSubtitleUrl.indexOf("/upload"));
                    String subtitleVideoPath = ffmpegUtils.AddSubtitlesForVideo(videoPath, subtitleFilePath);
                    if (StringUtils.isNotEmpty(subtitleVideoPath)) {
                        String subtitleVideoUrl = ServletUtils.getDomainUrl() + "/profile" + subtitleVideoPath.substring(subtitleVideoPath.indexOf("/upload/"));
                        stuQuestionLibraryRy.setSubtitleVideoUrl(subtitleVideoUrl);
                    }
                }

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

        }

        return stuQuestionLibraryRy;
    }


    /**
     * 新增stuQuestionLibrary
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:add')")
    @Log(title = "新增题库内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StuQuestionLibraryRy stuQuestionLibraryRy) {
        int result1 = stuQuestionLibraryRyService.insertStuQuestionLibraryRy(stuQuestionLibraryRy);
        int result2 = AddQuestionRelation(stuQuestionLibraryRy);
        return toAjax(result1 * result2);
    }

    @Transactional
    public int AddStuQuestionLibrary(StuQuestionLibraryRy stuQuestionLibraryRy) {
        String content = stuQuestionLibraryRy.getQuestionWord();
        if (StringUtils.isNotEmpty(content)) {
            String pdfUrl = PdfUtil.createPdfFile(content);
            if (StringUtils.isNotEmpty(pdfUrl)) {
                stuQuestionLibraryRy.setFileUrl(pdfUrl);
            }
        }

        int result1 = stuQuestionLibraryRyService.insertStuQuestionLibraryForCourse(stuQuestionLibraryRy);
        int result2 = AddQuestionRelation(stuQuestionLibraryRy);
        //只有添加万英达课程学习内容时才添加生词
        if (stuQuestionLibraryRy.getQuestionTypeId() == 44) {
            AddWordRelation(stuQuestionLibraryRy);
        }

        return result1 * result2;
    }

    /**
     * 添加课程生词
     *
     * @return
     */
    public int AddWordRelation(StuQuestionLibraryRy stuQuestionLibraryRy) {
        List<StuQuestionRelationRy> questionRelationRyList = new ArrayList<>();
        int result = 1;
        String word_text = stuQuestionLibraryRy.getQuestionWord();
        if (StringUtils.isNotEmpty(word_text)) {
            List<String> PrevCourseWords = getPrevCourseWords(stuQuestionLibraryRy.getCourseSort());
            List<String> words = StringUtils.arraysDistinct(word_text.toLowerCase().split(" "));
            for (String w : words) {
                wordLibrary word = wordLibraryService.selectwordLibraryByName(w);
                if (word != null && !PrevCourseWords.contains(word.getId()) && !wordIsExist(stuQuestionLibraryRy, word.getId())) {
                    StuQuestionRelationRy stuQuestionRelation = new StuQuestionRelationRy();
                    stuQuestionRelation.setId(IdUtils.simpleUUID());
                    stuQuestionRelation.setBussId(stuQuestionLibraryRy.getBussId());
                    stuQuestionRelation.setBussTableName("edu_word_library");
                    stuQuestionRelation.setWordId(word.getId());
                    stuQuestionRelation.setCourseId(stuQuestionLibraryRy.getCourseId());
                    stuQuestionRelation.setQuestionLibraryId(stuQuestionLibraryRy.getId());
                    questionRelationRyList.add(stuQuestionRelation);
                }
            }
            if (questionRelationRyList.size() > 0) {
                result = stuQuestionRelationRyService.insertStuQuestionRelationList(questionRelationRyList);
            }
        }
        return result;
    }


    /**
     * 判断同一课程下单词是否存在
     *
     * @param stuQuestionLibrary
     * @param wordId
     * @return
     */
    public boolean wordIsExist(StuQuestionLibraryRy stuQuestionLibrary, String wordId) {
        StuQuestionRelationRy stuQuestionRelation = new StuQuestionRelationRy();
        stuQuestionRelation.setCourseId(stuQuestionLibrary.getCourseId());
        stuQuestionRelation.setWordId(wordId);
        List<StuQuestionRelationRy> stuQuestionRelationRyList = stuQuestionRelationRyService.selectStuQuestionRelationRyList(stuQuestionRelation);
        if (stuQuestionRelationRyList != null && stuQuestionRelationRyList.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取上一个课程下的生词id
     */
    private List<String> getPrevCourseWords(Long courseSort) {
        StuProductCatalog productCatalog = new StuProductCatalog();
        List<String> wordList = new ArrayList<>();
        productCatalog.setCourseSort(courseSort - 1);
        productCatalog.setCatalogLevel(3L);
        List<StuProductCatalog> productCatalogList = productCatalogService.selectProductCatalogList(productCatalog);
        if (productCatalogList != null && productCatalogList.size() > 0) {
            StuProductCatalog catalog = productCatalogList.get(0);
            StuQuestionRelationRy questionRelation = new StuQuestionRelationRy();
            questionRelation.setCourseId(catalog.getId());
            List<StuQuestionRelationRy> questionRelationRyList = stuQuestionRelationRyService.selectStuQuestionRelationRyList(questionRelation);
            for (StuQuestionRelationRy qr : questionRelationRyList) {
                wordList.add(qr.getWordId());
            }
        }

        return wordList;
    }


    /**
     * 添加题库关系表
     *
     * @param stuQuestionLibraryRy
     * @return
     */
    public int AddQuestionRelation(StuQuestionLibraryRy stuQuestionLibraryRy) {
        StuQuestionRelationRy stuQuestionRelation = new StuQuestionRelationRy();
        stuQuestionRelation = (StuQuestionRelationRy) BeanUtils.initBeanPublicProperties(stuQuestionRelation, "add");
        stuQuestionRelation.setBussId(stuQuestionLibraryRy.getBussId());
        stuQuestionRelation.setBussTableName("stu_question_library");
        stuQuestionRelation.setQuestionLibraryId(stuQuestionLibraryRy.getId());
        stuQuestionRelation.setSortNum(Integer.parseInt(stuQuestionLibraryRy.getSortNum()));
        int result = stuQuestionRelationRyService.insertStuQuestionRelationRy(stuQuestionRelation);
        return result;
    }

    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:add')")
    @Log(title = "stuQuestionLibrary", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult addStuQuestionLibraryRy(@RequestBody StuQuestionLibraryRy stuQuestionLibraryRy) {
        return toAjax(stuQuestionLibraryRyService.addStuQuestionLibraryRy(stuQuestionLibraryRy));
    }

    /**
     * 修改stuQuestionLibrary
     */
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:edit')")
    @Log(title = "修改课程内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StuQuestionLibraryRy stuQuestionLibraryRy) {
        stuQuestionLibraryRy.setUpdateDate(DateUtil.date());
        return toAjax(stuQuestionLibraryRyService.updateStuQuestionLibraryRy(stuQuestionLibraryRy));
    }

    /**
     * 修改课程相关内容
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:edit')")
    @Log(title = "修改课程学习内容", businessType = BusinessType.UPDATE)
    @PutMapping("/updateQuestionLibraryForCourse")
    public AjaxResult updateQuestionLibraryForCourse(@RequestBody StuQuestionLibraryRy stuQuestionLibrary) {
        stuQuestionLibrary.setUpdateDate(new Date());
        stuQuestionLibrary.setUpdateBy(SecurityUtils.getUsername());
        stuQuestionLibrary = setProps(stuQuestionLibrary);
        int result1 = stuQuestionLibraryRyService.updateStuQuestionLibraryRy(stuQuestionLibrary);
        int result2 = stuQuestionRelationRyService.deleteStuQuestionRelationRyByQuestionIds(new String[]{stuQuestionLibrary.getId().toString()});
        int result3 = AddQuestionRelation(stuQuestionLibrary);
        int result4 = AddWordRelation(stuQuestionLibrary);
        return toAjax(result1);
    }

    /**
     * 删除stuQuestionLibrary
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:remove')")
    @Log(title = "stuQuestionLibrary", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        int result1 = stuQuestionLibraryRyService.deleteStuQuestionLibraryRyByIds(ids);
        int result2 = stuQuestionPaperRelationService.deleteStuQuestionPaperRelationBylibraryIds(ids);
        int result3 =stuQuestionRelationRyService.deleteStuQuestionRelationRyByQuestionIds(ids);
        return toAjax(result1);
    }

    /**
     * 删除课程相关内容
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('stu:questionLibrary:remove')")
    @Log(title = "stuQuestionLibrary", businessType = BusinessType.DELETE)
    @DeleteMapping("/delQuestionLibraryForCourse/{ids}")
    public AjaxResult delQuestionLibraryForCourse(@PathVariable String[] ids) {
        int result1 = stuQuestionLibraryRyService.deleteStuQuestionLibraryRyByIds(ids);
        int result2 = stuQuestionRelationRyService.deleteStuQuestionRelationRyByQuestionIds(ids);
        //int result3 = stuQuestionRelationRyService.deleteStuQuestionRelationRyByBussIds(ids);
        return toAjax(result1);
    }
}
